package com.exercise.core.deploy;/**
 * Created by kete on 2017-05-05.
 */

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * 作者：kete
 * 创建时间：2017-05-05 15:37
 * 功能描述：
 * 版本：
 */
public class ModuleManager {

    private static Logger logger = LoggerFactory.getLogger(ModuleManager.class);

    private static PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();

    private static String MODULE_FLAG = "/module/";
    private static String VIEWS_FLAG = "/views/";
    private static String JS_FLAG = "/js/";
    private static String CSS_FLAG = "/css/";
    private static String IMAGES_FLAG = "/images/";

    public static String webdocsDir = "";
    public static String viewsDir = "";



    public static void deploy() {

        try {
            logger.info(">>>>>发布内核");
            exportCore(webdocsDir + "webdocs/js",JS_FLAG);
            exportCore(webdocsDir + "webdocs/css",CSS_FLAG);
            exportCore(webdocsDir + "webdocs/images",IMAGES_FLAG);
            exportCore(viewsDir,VIEWS_FLAG);
            logger.info(">>>>>发布内核完成");

            exportCommon(viewsDir,VIEWS_FLAG);

            logger.info(">>>>>发布模块");
            exportModule(webdocsDir + "webdocs/js",JS_FLAG);
            exportModule(viewsDir,VIEWS_FLAG);
            logger.info(">>>>>发布模块完成");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void deployViews(String saveDir) throws Exception {

        exportModule(saveDir,JS_FLAG);
    }

    public static void deployJs(String saveDir) throws Exception {

        exportModule(saveDir,JS_FLAG);
    }

    private static void exportCommon(String saveDir,String flag) throws Exception {

        Resource[] resources = resolver.getResources("classpath*:com/exercise/common"+flag+"**");
        String path = null;
        String filename = null;
        File file = null;
        OutputStream output = null;
        InputStream input = null;
        for (Resource resource : resources) {

            if(resource.contentLength() <= 0) continue;
            if(resource instanceof FileSystemResource) {
                FileSystemResource fileResource = (FileSystemResource)resource;
                if(fileResource.getFile().isDirectory()) continue;
            }

            path = resource.getURL().getPath();
            int j = path.lastIndexOf(flag);

            filename = saveDir + "/" + path.substring(j + flag.length());
            mkdirs(FilenameUtils.getFullPath(filename));

            file = new File(filename);
            try {
                output = new FileOutputStream(file);
                input = resource.getInputStream();
                IOUtils.copy(input, output);
            } catch(Exception e) {
                e.printStackTrace();
            } finally {
                IOUtils.closeQuietly(input);
                IOUtils.closeQuietly(output);
            }

            file.setLastModified(resource.lastModified());
        }
    }


    private static void exportCore(String saveDir,String flag) throws Exception {

        Resource[] resources = resolver.getResources("classpath*:com/exercise/core"+flag+"**");
        String path = null;
        String filename = null;
        File file = null;
        OutputStream output = null;
        InputStream input = null;
        for (Resource resource : resources) {

            if(resource.contentLength() <= 0) continue;
            if(resource instanceof FileSystemResource) {
                FileSystemResource fileResource = (FileSystemResource)resource;
                if(fileResource.getFile().isDirectory()) continue;
            }

            path = resource.getURL().getPath();
            int j = path.lastIndexOf(flag);

            filename = saveDir + "/" + path.substring(j + flag.length());
            mkdirs(FilenameUtils.getFullPath(filename));

            file = new File(filename);
            try {
                output = new FileOutputStream(file);
                input = resource.getInputStream();
                IOUtils.copy(input, output);
            } catch(Exception e) {
                e.printStackTrace();
            } finally {
                IOUtils.closeQuietly(input);
                IOUtils.closeQuietly(output);
            }

            file.setLastModified(resource.lastModified());
        }
    }

    private static void exportModule(String saveDir,String flag) throws Exception {

        Resource[] resources = resolver.getResources("classpath*:com/exercise/**/module/**"+flag+"**");
        String path = null;
        String filename = null;
        File file = null;
        OutputStream output = null;
        InputStream input = null;
        String filePath = "";
        for (Resource resource : resources) {

            if(resource.contentLength() <= 0) continue;
            if(resource instanceof FileSystemResource) {
                FileSystemResource fileResource = (FileSystemResource)resource;
                if(fileResource.getFile().isDirectory()) continue;
            }

            path = resource.getURL().getPath();
            int i = path.lastIndexOf(MODULE_FLAG);
            int j = path.lastIndexOf(flag);

            String module = path.substring(i + MODULE_FLAG.length(), j);
//			filePath = saveDir + "/" + module;
//			filename = filePath + "/" + FilenameUtils.getName(path);

            String viewFile = path.substring(j + flag.length());
            filePath = saveDir + (StringUtils.equals("common",module)?"":"/" + module);
            if(StringUtils.isNotEmpty(viewFile)) {
                filename = filePath + "/" + viewFile;
            } else {
                filename = filePath + "/" + FilenameUtils.getName(path);
            }

            mkdirs(FilenameUtils.getFullPath(filename));

            file = new File(filename);
            try {
                output = new FileOutputStream(file);
                input = resource.getInputStream();
                IOUtils.copy(input, output);
            } catch(Exception e) {
                e.printStackTrace();
            } finally {
                IOUtils.closeQuietly(input);
                IOUtils.closeQuietly(output);
            }

            file.setLastModified(resource.lastModified());
        }
    }

    public static boolean mkdirs(String dir) {

        File fileDir = new File(dir);
        if(fileDir.exists()) return true;

        return fileDir.mkdirs();
    }
}
